/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.answer.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.ruoyi.answer.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.answer.common.annotation.Login;
import com.ruoyi.answer.entity.Answer;
import com.ruoyi.answer.entity.Question;
import com.ruoyi.answer.entity.TestPaper;
import com.ruoyi.answer.entity.User;
import com.ruoyi.answer.service.*;
import com.ruoyi.answer.tool.R;
import com.ruoyi.answer.tool.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 登录接口
 *
 * @author Mark sunlightcs@gmail.com
 */
@Slf4j
@RestController
@RequestMapping("/api")
@Api(tags = "试卷接口")
@AllArgsConstructor
public class TestPaperController {
   public AdminUserService adminUserService;
   public UserService userService;
   public AnswerService answerService;
   public TestPaperService testPaperService;
   public IQuestionService questionService;

    @PostMapping("/testPaper")
    @ApiOperation("试卷")
    public R testPaper(@RequestBody TestPaper testPaperEntity) {

        testPaperEntity.setCreateTime(new Date());
        testPaperEntity.setStatus("0");

        TestPaper byId = testPaperService.getById(testPaperEntity.getId());

        if (byId!=null){
            return R.ok();
        }
        testPaperService.save(testPaperEntity);

        List<TestPaper> list = testPaperService.lambdaQuery()
                .eq(TestPaper::getAccount, testPaperEntity.getAccount())
                .gt(TestPaper::getCreateTime, DateUtil.offsetDay(new Date(),-7))
                .ne(TestPaper::getName,testPaperEntity.getName())
                .groupBy(TestPaper::getName)
                .list();
        User one = userService.lambdaQuery().eq(User::getAccount, testPaperEntity.getAccount()).one();

        HashMap<String, Object> hashMap = new HashMap<>();
        for (TestPaper testPaper : list) {
            hashMap.put(testPaper.getName().split("_")[0],"1");
        }

        if(hashMap.size()>one.getNumber()){
            return R.error(501,"次数不足");
        }
        return R.ok();
    }


    @GetMapping("/testPaper")
    @ApiOperation("查询试卷")
    @Login
    public Result<List<TestPaper>> getTestPaper(TestPaper testPaperEntity) {
        User one = userService.lambdaQuery().eq(User::getAccount, testPaperEntity.getAccount()).last("limit 1").one();
       int size = testPaperService.list(
                new QueryWrapper<>(testPaperEntity)
                        .gt("create_time", DateUtil.offsetDay(new Date(),-7))
                        .like("create_time", "LX")
       ).size();
        List<TestPaper> list = testPaperService.list(
                new QueryWrapper<>(testPaperEntity)
                        .gt("create_time", DateUtil.offsetDay(new Date(),-7))
                        .orderByDesc("create_time")
                        .last("limit "+ (one.getNumber()+size)));
        for (TestPaper testPaper : list) {
            testPaper.setValue(JSONObject.parse(testPaper.getValue()+""));
        }
        return new Result<>(list);
    }

    @PostMapping("/answer")
    @ApiOperation("设置答案")
    public Result answer(@RequestBody Answer answer) {

        answer.setCreateTime(new Date());
        answerService.save(answer);

      try {
          Question question = new Question();
          TestPaper byId = testPaperService.getById(answer.getTestPaperId());
          if(byId!=null){
              question.setCourse(byId.getName());
          }
          question.setRemarks1(answer.getId());
          JSONObject value = JSONObject.parseObject(JSONObject.toJSONString(answer.getValue()));
          JSONObject jsonObject = value.getJSONObject("masterVersion").getJSONArray("questionUnitList").getJSONObject(0);
          question.setQuestionType(jsonObject.getString("questionType"));
          question.setAnswer("");
          try {
              JSONArray objectss = jsonObject.getJSONArray("rightAnswer");
              JSONArray questionOptionList = jsonObject.getJSONArray("questionOptionList");
              if("MULTIPLE_CHOICE".equals(question.getQuestionType())||"SINGLE_CHOICE".equals(question.getQuestionType())){
                  if(objectss!=null){
                      for (int ii = 0; ii < objectss.size(); ii++) {
                          String string = objectss.getString(ii);
                          int i2 = "A".toCharArray()[0] + ii;
                          question.setAnswer(  question.getAnswer()+" "+ (char)i2 +":" + questionOptionList.getJSONObject(Integer.parseInt(string)).getString("body"));
                      }
                  }
              }else{
                  question.setAnswer(objectss.getString(0));
              }

          } catch (Exception e) {
              log.error("保存question异常",e);
              return new Result();

          }

          question.setQuestionBody(jsonObject.getString("body"));
          question.setCreateTime(new Date());
          //questionService.lambdaUpdate().set(Question::getQuestionType,"判断题").eq(Question::getQuestionType,"TRUE_OR_FALSE").update();
          //questionService.lambdaUpdate().set(Question::getQuestionType,"选择题").eq(Question::getQuestionType,"SINGLE_CHOICE").update();
          //questionService.lambdaUpdate().set(Question::getQuestionType,"选择题").eq(Question::getQuestionType,"MULTIPLE_CHOICE").update();
          //questionService.lambdaUpdate().set(Question::getQuestionType,"问答").eq(Question::getQuestionType,"ESSAY").update();
          //questionService.lambdaUpdate().set(Question::getQuestionType,"填空").eq(Question::getQuestionType,"FILL_UP").update();
          if ("TRUE_OR_FALSE".equals(question.getQuestionType())) {
              question.setQuestionType("判断题");
          }else  if ("SINGLE_CHOICE".equals(question.getQuestionType())) {
              question.setQuestionType("选择题");
          }else  if ("MULTIPLE_CHOICE".equals(question.getQuestionType())) {
              question.setQuestionType("多选题");
          }else  if ("ESSAY".equals(question.getQuestionType())) {
              question.setQuestionType("问答");
          }else  if ("FILL_UP".equals(question.getQuestionType())) {
              question.setQuestionType("填空");
          }
          questionService.save(question);

      }catch (Exception e){
          log.error("保存question异常",e);
      }

        return new Result();
    }


    @GetMapping("/answer")
    @ApiOperation("获取答案")
    @Login
    public Result<List<Answer>> getAnswer(Answer answer) {
        //if(StrUtil.isEmptyIfStr(Answer.getTestPaperId())&&StrUtil.isEmptyIfStr(Answer.getId())){
        //    return new Result<List<Answer>>("500","错误");
        //}
        List<Answer> list = answerService.lambdaQuery().eq(Answer::getId, answer.getId()).list();
        for (Answer testPaper : list) {
            testPaper.setValue(JSONObject.parse(testPaper.getValue()+""));
        }

        return new Result<List<Answer>>(list);
    }
    @GetMapping("/typeConversion")
    @ApiOperation("typeConversion")
    public Result<List<Answer>> typeConversion() {

        List<TestPaper> list = testPaperService.lambdaQuery().list();


        for (TestPaper answer : list) {
          String value = answer.getValue().toString();
         byte[] bytes = HexUtil.decodeHex(value);
            Object deserialize = ObjectUtil.deserialize(bytes);
            answer.setValue(deserialize);

        }
        testPaperService.updateBatchById(list);
        return new Result<List<Answer>>();
    }

}
